import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/lib_user/user_manager.dart';
import 'package:ones/ui/action.dart';
import 'package:provider/provider.dart';

import '../../../../lib_basemodel/chat_room/kh_chat_room_seat_model.dart';
import '../../../../lib_basemodel/chat_room/kh_mic_seat_user_info_model.dart';
import '../../../../lib_network/http_api.dart';
import '../../../../lib_network/http_helper.dart';
import '../../../m_chatroom.dart';
import 'mic_seat_scene.dart';
import 'mic_seat_user_info_widget.dart';
import 'mic_seat_widget_model.dart';

import '../../../../../lib_runtime/extension/widget/widget_wrapper.dart';
import '../../../../../lib_runtime/extension/string_extension/string_text.dart';

///
///麦位列表
///
class MicSeatWidget extends StatelessWidget {
  MicSeatScene micSeatScene;

  MicSeatWidget({super.key, this.micSeatScene = MicSeatScene.ROOM});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProxyProvider<RootProxyModel, MicSeatWidgetModel>(
          create: (context) => MicSeatWidgetModel(micSeatScene: micSeatScene),
          update: (context, rootProxyModel, leafModel) {
            if (leafModel == null) throw ArgumentError.notNull('leafModel');
            leafModel.roomModel = rootProxyModel;
            return leafModel;
          },
        ),
      ],
      child: Column(
        children: [
          Consumer<MicSeatWidgetModel>(builder: (context, model, child) {
            return _buildContent(context, model);
          }),
        ],
      ),
    );
  }

  Widget _buildContent(BuildContext context, MicSeatWidgetModel model) {
    List<KHChatRoomSeatModel?>? tmpList =
        model.roomModel.roomEnterModel?.micList;

    if (tmpList == null) {
      return const SizedBox.shrink();
    }

    if (tmpList.length == 2) {
      return const SizedBox.shrink();
    } else if (tmpList.length == 4) {
      return const SizedBox.shrink();
    } else if (tmpList.length == 6) {
      // return Container()
      return const SizedBox.shrink();
    } else {
      return Container(
        height: 200,
        width: ScreenUtil().screenWidth - 9 * 2,
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 5,
            childAspectRatio: 1.0,
            mainAxisSpacing: 24, // 设置主轴方向（垂直方向）的间距为 24
            // crossAxisSpacing: 24, // 设置交叉轴方向（水平方向）的间距为 24
          ),
          itemCount: model.micCount,
          itemBuilder: (context, index) {
            return Column(
              children: [
                micHeaderWidget(tmpList[index]),
                const SizedBox(height: 5),
                micHeaderNameWidget(tmpList[index]),
              ],
            ).onClick(() {
              KHChatRoomSeatModel? tmpModel = tmpList[index];

              bool mick = tmpModel?.micUser?.userId != null;

              bool? roomOwner = model.roomModel.roomPageModel!.roomOwner;

              /// 如果麦上的userid 是当前的用户，表示自己下麦
              if (mick) {
                if (mick &&
                    tmpModel?.micUser?.userId == UserManager.instance.id) {
                  showRoomOwnerWidget(
                      context,
                      model,
                      index,
                      model.roomModel.roomEnterModel?.chatRoomModel?.roomInfo
                          ?.roomNo);
                } else {
                  showRoomOtherWidget(
                    context,
                    index,
                    roomNo: model.roomModel.roomEnterModel?.chatRoomModel
                        ?.roomInfo?.roomNo,
                    userId: tmpModel?.micUser?.userId ?? 0,
                    isOwner: roomOwner ?? false,
                  );
                }
              } else {
                model.onMicSeatClick(
                    context,
                    index,
                    model.roomModel.roomEnterModel?.chatRoomModel?.roomInfo
                        ?.roomNo);
              }
            });
          },
        ),
      );
    }
  }

  /// 这里的麦克风状态和底部状态栏的麦克状态保持一致
  Widget micHeaderWidget(KHChatRoomSeatModel? model) {
    final avatarStr = model?.micUser?.headPortraitsUrl;

    String? micName = model?.micUser?.nickname;
    return Container(
      // color: Colors.yellow,
      height: 48,
      width: 48,

      child: Stack(
        children: [
          JR
              .img(avatarStr ?? 'room/room_seat_default_icon.png')
              .corner(radius: 48 / 2.0),
          // if (micName != null)
          //   PositionedDirectional(
          //     end: 0,
          //     bottom: 0,
          //     child: SizedBox(
          //       width: 18,
          //       height: 18,
          //       child: micStatus ? null : JR.img('room/room_mic_off.png'),
          //     ),
          //   ),
        ],
      ),
    );
  }

  Widget micHeaderNameWidget(KHChatRoomSeatModel? model) {
    /// 判断是否是房主
    bool roomRole = model?.micUser != null && model?.micUser?.roomRole == 1;
    String? micName = model?.micUser?.nickname;
    Widget hostWidget = Row(
      children: [
        JR.img('room/room_mic_host_icon.png', width: 12, height: 12),
        const SizedBox(width: 2),
      ],
    );

    return Center(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (roomRole) hostWidget,
          (micName ?? '').text(
            color: const Color(0xFFFFFFFF),
            fontSize: 11,
            weight: TextFontWeight.bold,
            maxWidth: 50,
            maxLines: 1,
          )
        ],
      ),
    );
  }

  /// 房主点击自己
  void showRoomOwnerWidget(BuildContext context, MicSeatWidgetModel model,
      int position, String? roomNo) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 162,
          decoration: const BoxDecoration(
            color: Color(0xFFFFFFFF),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(18),
              bottomRight: Radius.circular(18),
            ),
          ),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 68,
                child: 'leave the mic'
                    .text(color: Color(0xFF000000), fontSize: 20)
                    .center(),
              ).onClick(() {
                model.onMicSeatDownClick(context, position, roomNo);
                Navigator.pop(context);
              }),
              Container(color: const Color(0xFFFAFAFA), height: 10),
              SizedBox(
                height: 74,
                child: 'Cancel'
                    .text(color: Color(0xFFA8A8A8), fontSize: 20)
                    .center(),
              ).onClick(() {
                Navigator.pop(context);
              }),
              const SizedBox(height: 10)
            ],
          ),
        );
      },
    );
  }

  /// 点击他人
  void showRoomOtherWidget(BuildContext context, int position,
      {String? roomNo, int? userId, bool? isOwner}) async {
    /// 先请求，在跳转页面
    var response = await HttpHelper.instance().post(
      HttpApi.userSimpleGet,
      body: {
        'roomNo': roomNo,
        'userId': userId,
      },
      showLoading: false,
      showToast: true,
    );
    if (response.isSuccess) {
      KhMicSeatUserInfoModel model =
          KhMicSeatUserInfoModel.fromJson(response.result);

      showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return MicSeatUserInfoWidget(
            isRoomOwner: isOwner,
            model: model,
          );
        },
      );
    }
  }
}
